import axios from 'axios'
import router from '@/router/pages'
import { Message } from 'element-ui';


// 设置域名

let BASEURL = defaultUrl
// let domain = document.domain
// let teamUrl = document.location.pathname.split('/')[1]
// if (domain == 'localhost') {
//   BASEURL ='http://10.150.33.126:8106/'  //本地
// }else if(document.location.origin=='http://bestsellerdmp.bestseller.com.cn') {
//   BASEURL='http://bestsellerdmp.bestseller.com.cn/'+teamUrl
// }else {
//   BASEURL =document.location.origin +'/'
// }

// 配置域名、超时时间（10s）
let $ = axios.create({
  baseURL: BASEURL,
  timeout: 30000
})

// 设置数据传输格式
// $.defaults.headers.post['Content-Type'] =
//   'application/x-www-form-urlencoded; charset=UTF-8'

// json转form data数据格式
// $.defaults.transformRequest = [
//   function(data) {
//     let ret = ''
//     for (let it in data) {
//       ret += encodeURIComponent(it) + '=' + (data[it]) + '&'
//     }
//     return ret
//   }
// ]

// 请求拦截器
$.interceptors.request.use(
  config => {
    // let logOnUser = JSON.parse(sessionStorage.getItem("logOnUser"))
    if (config.method == "get") {
      let soa_account = sessionStorage.getItem("soa_account");
      if (soa_account != "" && soa_account != null) {
        // config['params'] ={"soa_account":soa_account}

        config.headers.account = soa_account
      }
      //设置token的请求头
      const token = sessionStorage.getItem("soa_token")
      config.headers.token = `${token}`;
    } else {
      let soa_account = sessionStorage.getItem("soa_account");
      if (soa_account != "" && soa_account != null) {
        // config['params'] ={"soa_account":soa_account}

        config.headers.account = soa_account
      }
      //设置token的请求头
      const token = sessionStorage.getItem("soa_token")
      config.headers.token = `${token}`;
    }
    // config.headers.unitId = logOnUser.unitId;
    // config.headers.unitType = logOnUser.unitType;
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
$.interceptors.response.use(
  response => {
    const status = response.status
    if (response.data.code == 401 || response.data.code == 403) {
      window.location.href = "/login"
      // alert('登陆失败，请联系管理员')
      Message.error('登陆失败，请联系管理员')
    }
    if (response.data.code == 405) {
      sessionStorage.setItem("soa_account", "")
      sessionStorage.setItem("soa_token", "")
      window.location.href = "/login"
      // alert('该账号无权限')
      Message.error('该账号无权限')
    }
    return response
  },
  error => {
    Message.error('接口请求失败')
    return error
  }
)
export default {
  post: (url, data) => $.post(url, data),
  get: (url, data) => $.get(url, data),
  BASEURL
}
